/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mvc.example.presentation.view;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import javax.swing.event.EventListenerList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import mvc.example.presentation.events.DataEvent;
import mvc.example.presentation.listeners.StudentDataListener;
import mvc.example.bussines.domain.Student;
import mvc.example.presentation.controller.StudentsController;
import mvc.example.presentation.listeners.StudentSelectedListener;
import mvc.example.presentation.model.StudentsModel;
import mvc.example.presentation.model.StudentsTableModel;

/**
 *
 * @author Zeta
 */
public class StudentsView extends javax.swing.JFrame {

    protected StudentDataListener dataListener;
    private StudentsController controller;
    protected EventListenerList listenerList = new EventListenerList();
    private Handler handler = null;

    /**
     * Creates new form StudentsView
     */
    public StudentsView(final StudentsController controller) {
        initComponents();
        this.controller = controller;
        installListeners();
        this.jTableStudents.setModel(new StudentsTableModel(controller.getStudentsModel().getStudents()));
        this.jTableStudents.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
               fireSelectedStudentChange(e.getSource(),e.getFirstIndex());
            }
        });
//        this.jTableStudents.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
//            @Override
//            public void valueChanged(ListSelectionEvent e) {
//                controller.contentsChanged(new DataEvent(e.getSource(), DataEvent.CONTENTS_CHANGED, e.getFirstIndex()));
//            }
//        });
    }
       
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jPanelSearch = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jComboBoxSearchBy = new javax.swing.JComboBox();
        jTextFieldSearch = new javax.swing.JTextField();
        jButtonSearch = new javax.swing.JButton();
        jPanelStudentTable = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableStudents = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jButtonAdd = new javax.swing.JButton();
        jButtonEdit = new javax.swing.JButton();
        jButtonEliminar = new javax.swing.JButton();

        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.PAGE_AXIS));

        jLabel2.setFont(new java.awt.Font("Rockwell", 1, 24)); // NOI18N
        jLabel2.setText("Alumnos");
        getContentPane().add(jLabel2);

        jPanelSearch.setBorder(javax.swing.BorderFactory.createTitledBorder("Buscar"));
        jPanelSearch.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jPanelSearch.setMaximumSize(new java.awt.Dimension(22255, 57));
        jPanelSearch.setLayout(new javax.swing.BoxLayout(jPanelSearch, javax.swing.BoxLayout.LINE_AXIS));

        jLabel1.setText("buscar por:");
        jPanelSearch.add(jLabel1);

        jComboBoxSearchBy.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Legajo", "Nombre", "Apellido" }));
        jComboBoxSearchBy.setPreferredSize(new java.awt.Dimension(115, 28));
        jPanelSearch.add(jComboBoxSearchBy);
        jPanelSearch.add(jTextFieldSearch);

        jButtonSearch.setText("Buscar");
        jPanelSearch.add(jButtonSearch);

        getContentPane().add(jPanelSearch);

        jPanelStudentTable.setLayout(new javax.swing.BoxLayout(jPanelStudentTable, javax.swing.BoxLayout.LINE_AXIS));

        jTableStudents.setModel(new StudentsTableModel(new ArrayList<Student>()));
        jTableStudents.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        jScrollPane1.setViewportView(jTableStudents);

        jPanelStudentTable.add(jScrollPane1);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones"));
        jPanel1.setMaximumSize(new java.awt.Dimension(79, 1500));
        jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.PAGE_AXIS));

        jButtonAdd.setText("Nuevo");
        jButtonAdd.setMaximumSize(new java.awt.Dimension(100, 57));
        jButtonAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddActionPerformed(evt);
            }
        });
        jPanel1.add(jButtonAdd);

        jButtonEdit.setText("Editar");
        jButtonEdit.setMaximumSize(new java.awt.Dimension(100, 57));
        jButtonEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonEditActionPerformed(evt);
            }
        });
        jPanel1.add(jButtonEdit);

        jButtonEliminar.setText("Eliminar");
        jButtonEliminar.setMaximumSize(new java.awt.Dimension(100, 57));
        jPanel1.add(jButtonEliminar);

        jPanelStudentTable.add(jPanel1);

        getContentPane().add(jPanelStudentTable);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddActionPerformed
         controller.newStudent();
    }//GEN-LAST:event_jButtonAddActionPerformed

    private void jButtonEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEditActionPerformed
        controller.editStudent();
    }//GEN-LAST:event_jButtonEditActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAdd;
    private javax.swing.JButton jButtonEdit;
    private javax.swing.JButton jButtonEliminar;
    private javax.swing.JButton jButtonSearch;
    private javax.swing.JComboBox jComboBoxSearchBy;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanelSearch;
    private javax.swing.JPanel jPanelStudentTable;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableStudents;
    private javax.swing.JTextField jTextFieldSearch;
    // End of variables declaration//GEN-END:variables

    private class Handler implements StudentDataListener, PropertyChangeListener {


        @Override
        public void contentsChanged(DataEvent e) {
            if (e.getType() == DataEvent.NEW_DATA) {
                StudentsModel source = (StudentsModel) e.getSource();
                ((StudentsTableModel) jTableStudents.getModel()).setStudents(source.getStudents());
            }
        }

        @Override
        public void propertyChange(PropertyChangeEvent evt) {

            StudentsController studentsController = (StudentsController) evt.getSource();
            String propertyName = evt.getPropertyName();

            if ("model".equals(propertyName)) {
                StudentsModel newModel = (StudentsModel) evt.getNewValue();
                StudentsModel oldModel = (StudentsModel) evt.getOldValue();
                if (oldModel != null && dataListener != null) {
                    oldModel.removeDataListener(dataListener);
                }
                if (newModel != null && dataListener != null) {
                    newModel.addDataListener(dataListener);
                }

            }
        }
    }

    private Handler getHandler() {
        if (handler == null) {
            handler = new Handler();
        }
        return handler;
    }

    private StudentDataListener createDataListener() {
        return getHandler();
    }

    protected void installListeners() {
        if (controller.getStudentsModel() != null) {
            dataListener = createDataListener();
            controller.getStudentsModel().addDataListener(dataListener);
        }
      
        listenerList.add(StudentSelectedListener.class, controller);
    }
    
     private void fireSelectedStudentChange(Object source,int index0) {
        if(index0 < 0){
            return;
        }
        Student student = ((StudentsTableModel)jTableStudents.getModel()).getStudent(index0);
        StudentSelectedListener[] listeners = listenerList.getListeners(StudentSelectedListener.class);
	DataEvent e = null;
        
	for (int i = 0; i < listeners.length ; i++) {
	   
		if (e == null) {
		    e = new DataEvent(student, DataEvent.SELECTED_DATA, index0);
		}
		listeners[i].selectedChange(e);
	           
	}
      }
}
